﻿using Microsoft.AspNetCore.Mvc;
using ManageSystem.Model;
using System.Threading.Tasks;
using ManageSystem.Service;
using ManageSystem.Common.Helper;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using System;
using ManageSystem.AuthorizationRequirement;
using System.Linq;

namespace ManageSystem.Controllers
{
    /// <summary>
    /// login
    /// </summary>
    [Route("ManageSystem/[controller]/[action]")]
    [ApiController]
    [Produces("application/json")]
    public class UserController : ControllerBase
    {
        public UserService userService = new UserService();

        // 构造函数注入
        private PermissionRequirement permissionRequirement;
        public UserController(PermissionRequirement permissionRequirement)
        {
            this.permissionRequirement = permissionRequirement;
        }

        ///<summary>
        ///登录
        ///</summary>
        ///<param name="username"></param>
        ///<param name="password"></param>
        ///<returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetToken(string username, string password)
        {
            // query by user_name , return null if there is no user_name in the db
            User user = await userService.QueryUserByUserName(username);



            // invalid username or pwd
            if (user == null || !password.Equals(user.password))
            {
                return Unauthorized("用户名或密码错误");
            }
            /*
                        if(user.permissionString == null || user.permissionString == "")
                        {
                            user.permissionString = "updateMyUser,";
                        }*/

            // successfully login
            string[] userPermissions = user.permissionString.Split(",");


            // generate token
            string jwtStr = JwtHelper.IssueJwt(user);

            // 保存权限
            permissionRequirement.Permissions = new List<PermissionData>
            {
            };

            // 分配该用户的权限（根据数据库中存储的字段）
            foreach (string userpermission in userPermissions)
            {
                // 如果用户权限数组中的值存在于Map中就添加权限
                if (PermissionUrlMap.permissionUrlMap.ContainsKey(userpermission))
                {
                    permissionRequirement.Permissions.Add(new PermissionData(username, PermissionUrlMap.permissionUrlMap[userpermission]));
                }

            }

            return Ok(jwtStr);
        }

        ///<summary>
        ///获取当前用户信息(当前权限，无法修改)
        ///</summary>
        ///<param name="username"></param>
        ///<returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryNowUser(string username)
        {
            User user = await userService.QueryUserByUserName(username);

            if (user != null)
            {
                return Ok(user);
            }
            else
            {
                return NotFound("当前用户不存在！");
            }
        }

        ///<summary>
        ///查询当前所有账户名(选择项目负责人时使用),无需权限
        ///</summary>
        ///<returns></returns>
        [HttpGet]
        public async Task<IActionResult> QueryUserNameList()
        {
            List<User> users = await userService.QueryAll();

            List<string> userNameList = new();
            // admin账户不传
            users = users.Where(user => user.userRole != "admin").ToList();

            users.ForEach(user =>
            {
                userNameList.Add(user.username);
            });

            return Ok(userNameList);
        }



        ///<summary>
        ///修改当前用户信息(用户名和密码)
        ///</summary>
        ///<param name="newUserame"></param>
        ///<param name="newPassword"></param>
        ///<param name="userID"></param>
        ///<returns></returns>
        [Authorize(Policy = "Permission")]
        [HttpPut]
        public async Task<IActionResult> UpdateMyUser(string newUserame, string newPassword, int userID)
        {
            // my user
            User user = await userService.QueryByPrimaryKey(userID);

            if (user.username == newUserame)
            {
                return NotFound("用户名重复，请重新输入！");
            }
            else
            {
                user.username = newUserame;
                user.password = newPassword;
                bool isUpdatd = await userService.Update(user);
                if (isUpdatd)
                {
                    return Ok("更新用户信息成功，请重新登陆");
                }
                else
                {
                    return NotFound("更新用户信息失败");
                }
            }
        }

        // 0------------------------admin----------------------------

        ///<summary>
        ///添加用户（admin）
        ///</summary>
        ///<param name="username"></param>
        ///<param name="password"></param>
        ///<param name="permissionString"></param>
        ///<returns></returns>
        [Authorize(Roles = "admin")]
        [HttpPost]
        public async Task<IActionResult> AddUserByAdmin(string username, string password, string permissionString)
        {
            User user = await userService.QueryUserByUserName(username);

            if (user != null)
            {
                return NotFound("用户名重复，请重新输入！");
            }
            else
            {
                bool isAdded = await userService.Add(new User(username, password, permissionString, "user"));

                if (isAdded)
                {
                    return Ok($"添加用户成功[{username}]成功");

                }
                else
                {
                    return NotFound("添加失败");
                }
            }
        }


        ///<summary>
        ///删除用户
        ///</summary>
        ///<param name="userID"></param>
        ///<returns></returns>
        [Authorize(Roles = "admin")]
        [HttpDelete]
        public async Task<IActionResult> DeleteUserByAdmin(int userID)
        {
            bool isDeleted = await userService.DeleteByPrimaryKey(userID);
            if (isDeleted)
            {
                return Ok("删除用户成功");
            }
            else
            {
                return NotFound("删除失败！");
            }
        }

        ///<summary>
        ///修改用户（管理员）
        ///</summary>
        ///<param name="username"></param>
        ///<param name="password"></param>
        ///<param name="permissionString"></param>
        ///<param name="userID"></param>
        ///<returns></returns>
        [Authorize(Roles = "admin")]
        [HttpPut]
        public async Task<IActionResult> UpdateUserByAdmin(string username, string password, string permissionString, int userID)
        {
            // user to be updated
            User user = await userService.QueryByPrimaryKey(userID);
            if (user.username != username)
            {
                return NotFound("用户名重复，请重新输入！");
            }
            else
            {
                user.username = username;
                user.password = password;
                user.permissionString = permissionString;
                bool isUpdatd = await userService.Update(user);
                if (isUpdatd)
                {
                    return Ok("更新用户信息成功");
                }
                else
                {
                    return NotFound("更新用户信息失败");
                }
            }
        }

        ///<summary>
        ///查询所有用户(admin)
        ///</summary>
        ///<returns></returns>
        [Authorize(Roles = "admin")]
        [HttpGet]
        public async Task<IActionResult> QueryAllUserByAdmin()
        {
            List<User> users = await userService.QueryAll();

            // admin账户不传
            users = users.Where(user => user.userRole != "admin").ToList();

            return Ok(users);
        }

        // --------进入子系统的权限(函数体为空，只用来进行身份认证)---------------

        ///<summary>
        ///进入立项系统
        ///</summary>
        ///<returns></returns>
        [Authorize(Policy = "Permission")]
        [HttpGet]
        public void ToProjectSystem()
        {
        }

        ///<summary>
        ///进入收入流水系统
        ///</summary>
        ///<returns></returns>
        [Authorize(Policy = "Permission")]
        [HttpGet]
        public void ToIncomeStreamSystem()
        {
        }

        ///<summary>
        ///进入支出流水系统
        ///</summary>
        ///<returns></returns>
        [Authorize(Policy = "Permission")]
        [HttpGet]
        public void ToOutlayStreamSystem()
        {
        }

        ///<summary>
        ///进入管理员系统
        ///</summary>
        ///<returns></returns>
        [Authorize(Roles = "admin")]
        [HttpGet]
        public void ToAdminSystem()
        {
        }


        /// <summary>
        /// 解析Token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public IActionResult ParseToken()
        {
            //需要截取Bearer 
            var tokenHeader = HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
            var user = JwtHelper.SerializeJwt(tokenHeader);
            return Ok(user);

        }

    }
}
